<template>
  <div class="page-container">
    <list-searcher :searchList="searchList" v-model:searchForm="queryParam" @loadData="handleOk">
      <template #companyName="{ searchForm }">
        <a-select
          v-model="searchForm.id"
          :options="companyNameList"
          placeholder="请选择"
          allow-clear
          allow-search
          :filter-option="false"
          @search="handleSearch"
          @popup-visible-change="(visible) => visible && queryCompanyNameList()"
        />
      </template>
    </list-searcher>

    <a-alert type="error" class="items-start mb-4">
      <template #icon>
        <icon-exclamation-circle-fill />
      </template>
      <div class="font-medium text-red-500">
        <div>
          1、创建新企业账号，首次登录后需拉取交管网站违章数据，请等待2-3小时后再发起违章查询，如拉取数据过程中账号登出，不影响拉取进度，重新登录即可
        </div>
        <div> 2、在启程登录违章查询账号，后又登录交管平台，启程会被自动登退，如需查询请重新登录 </div>
        <div> 3、账号登录后会保留3-7天，当状态变更为未登录时，如需查询请重新登录 </div>
        <div> 4、新创建企业账号后，需联系启程运营配置信息，配置完成后才可登录及查询 </div>
        <div> 5、当天发生的违章，为保证数据准确及完善，请隔天查询 </div>
      </div>
    </a-alert>

    <table-index :table="table" @loadData="loadData">
      <template #table-summary>
        <div class="flex items-center">
          账户余额：
          <span class="num">{{ accountInfo.accountAmount ?? '-' }}</span>
          <span class="ml-1">元</span>
          <a-tag v-if="accountInfo.accountAmount < 100" class="ml-2" size="small" color="red" :default-checked="true">
            余额不足，尽快充值
          </a-tag>
          <a-divider direction="vertical" />
          <a-tooltip content="有效查询包含：有违章记录（包含新违章、历史违章状态变更、历史违章状态无变更）、无违章记录等">
            <icon-exclamation-circle style="font-size: 16px; color: #165dff" />
          </a-tooltip>
          <span>有效查询总数：</span>
          <span class="num">{{ accountInfo.validQueryCount ?? '-' }}</span>
          <span class="ml-1">条</span>
        </div>
      </template>
      <!-- 关联车辆 -->
      <template #carCount="{ record }">
        <template v-if="record.carCount">
          <span>{{ record.carCount }}</span>
          <a-link class="ml-2" @click="() => onALinkClick(record)">查看</a-link>
        </template>
      </template>
      <!-- 账号状态 -->
      <template #status="{ record }">
        <div>{{ record.statusName }}</div>
        <span v-if="record.status == 2" class="text-red-500 bg-red-50 px-2 py-0.5 font-medium text-xs">
          {{ record.openErrorMsg }}
        </span>
      </template>
      <!-- 账号登录状态 -->
      <template #loginStatus="{ record }">
        <div class="flex items-center loginStatus-wrapper">
          <span class="loginStatus-icon" :class="loginStatusClassName(record.loginStatus)"></span>
          <span>{{ record.loginStatusName }}</span>
        </div>
      </template>
      <!-- 最近数据更新时间 -->
      <template #syncDate="{ record }">
        <div>{{ record.syncDate }} {{ record.syncStatusName }}</div>
      </template>
    </table-index>
  </div>
  <!-- 登录 -->
  <LoginModal ref="loginRef" @loginSuccess="loginSuccess" @close="handleAccountInfo" />
  <!-- 查询违章弹窗 -->
  <violationQueryModal
    v-model:visible="violationQueryVisible"
    :options="violationQueryOptions"
    @onBeforeOk="loadData"
    @close="handleAccountInfo"
  />
  <!-- 添加/修改账号 -->
  <addAccountModal
    v-model:visible="addAccountVisible"
    :options="operatesCurrentOptions"
    @onBeforeOk="loadData"
    @close="handleAccountInfo"
  />
  <!-- 查询记录弹窗 -->
  <queryRecordModal ref="queryRecordRef" @close="handleAccountInfo" />
  <!-- 关联车辆弹窗 -->
  <carCountModal v-model:visible="carCountVisible" :options="carCountOptions" @close="handleAccountInfo" />
  <!-- 导入弹窗 -->
  <import-modal
    ref="imoportRef"
    action="/violation/queryAccount/importExcel"
    download-import="/违章查询账号导入模板.xlsx"
    @ok="loadData"
    @close="handleAccountInfo"
  />
</template>

<script setup lang="ts" name="CarViolationQuery">
  import addAccountModal from './modal/add-account-modal.vue'
  import queryRecordModal from './modal/query-record-modal.vue'
  import violationQueryModal from './modal/violation-query-modal.vue'
  import carCountModal from './modal/car-count-modal.vue'
  import LoginModal from './modal/login-model.vue'
  import dayjs from 'dayjs'

  import { useFetchTableDataApi, useTable } from '@/hooks/table'
  import { computed, onMounted, reactive, ref } from 'vue'
  import { getViolationQueryList, getAccountInfo, queryCompanyName } from '@/api/asset/carViolation'

  // 查询记录弹窗ref
  const queryRecordRef = ref<any>(null)
  const addAccountVisible = ref(false)
  const violationQueryVisible = ref(false)
  const carCountVisible = ref(false)
  const operatesCurrentOptions = ref({})
  const violationQueryOptions = ref({})
  const queryParam = reactive({})
  const imoportRef = ref<any>(null)
  const loginRef = ref<any>(null)
  const companyNameList = ref([])

  const searchList = computed(() => [
    { label: '企业名称', prop: 'id', slot: 'companyName' },
    { label: '车牌号', prop: 'licenseNoLike', type: 'a-input' },
  ])

  const table = useTable({
    columns: [
      {
        title: '企业名称',
        dataIndex: 'accountEpName',
        fixed: 'left',
      },
      {
        title: '统一社会信用代码',
        dataIndex: 'socialCreditNo',
        width: 150,
      },
      {
        title: '企业账号',
        dataIndex: 'account',
      },
      {
        title: '关联车辆',
        dataIndex: 'carCount',
        titleTooltipContent: '关联车辆为所选企业在交管网站中存在的车辆',
        slotName: 'carCount',
        width: 110,
      },
      {
        // status: 0 未开通 1 已开通 2 开通失败
        title: '账号状态',
        dataIndex: 'status',
        slotName: 'status',
      },
      {
        title: '查询违章时间',
        width: 200,
        render: (record: any) => {
          let queryTimeShow = ''
          if (record.queryTime) {
            queryTimeShow = dayjs(record.queryTime).format('YYYY年M月D日')
          }
          return `从${queryTimeShow}后查询违章`
        },
      },
      {
        // loginStatus: 0 未登录 1 已登录 3 登录失败 4 二维码超时
        title: '账号登录状态',
        dataIndex: 'loginStatus',
        slotName: 'loginStatus',
      },
      {
        title: '有效查询总数',
        dataIndex: 'validQueryCount',
      },
      {
        title: '最近查询时间',
        dataIndex: 'lastQueryTime',
        width: 170,
      },
      {
        title: '最近查询有效数',
        dataIndex: 'lastValidQueryCount',
      },
      {
        title: '最近数据更新时间',
        dataIndex: 'syncDate',
        slotName: 'syncDate',
        width: 170,
      },
    ],
    operates: [
      {
        label: '登录',
        // status: 0 未开通 1 已开通 2 开通失败
        // loginStatus: 0 未登录 1 已登录 3 登录失败 4 二维码超时
        show: (record: any) => record.status == 1 && record.loginStatus != 1,
        permission: 'svms:asstes:violation:query.login',
        method: (record: any) => {
          loginRef.value.open(record, 'login')
        },
      },
      {
        label: '查询违章',
        show: (record: any) => record.status == 1 && record.loginStatus == 1,
        permission: 'svms:asstes:violation:query.query',
        method: (record: any) => {
          violationQueryVisible.value = true
          violationQueryOptions.value = { ...record, btnType: 'query' }
        },
      },
      {
        label: '修改账号及车辆',
        permission: 'svms:asstes:violation:query.update',
        method: (record: any) => {
          addAccountVisible.value = true
          operatesCurrentOptions.value = record
        },
      },
      {
        label: '查询记录',
        permission: 'svms:asstes:violation:query.queryRecord',
        method: (record: any) => {
          queryRecordRef.value.open({
            epId: record.epId,
            accountId: record.id,
            companyName: record.accountEpName,
          })
        },
      },
    ],
    buttons: [
      {
        mode: 'import',
        label: '导入账号',
        permission: 'svms:asstes:violation:query.import',
        method: () => {
          imoportRef.value.show()
        },
      },
      {
        type: 'primary',
        label: '添加账号',
        icon: 'plus',
        permission: 'svms:asstes:violation:query.create',
        method: () => {
          addAccountVisible.value = true
          operatesCurrentOptions.value = {}
        },
      },
    ],
  })

  const loginStatusClassName = (status: number) => {
    switch (status) {
      case 1:
        return 'open'
      default:
        return 'close'
    }
  }

  const carCountOptions = ref<any>({})
  const onALinkClick = (record: any) => {
    console.log('onALinkClick', record)
    carCountVisible.value = true
    carCountOptions.value = record
  }

  const loadData = useFetchTableDataApi(table, queryParam, getViolationQueryList)

  // 查询账户信息
  const accountInfo = ref<any>({})
  const handleAccountInfo = () => {
    getAccountInfo().then((res: any) => {
      accountInfo.value = res.result
    })
  }

  // 获取企业名称
  // 企业名称是动态的，导入和新增都需要重新获取
  const queryCompanyNameList = (accountEpNameLike?: string) => {
    queryCompanyName({ accountEpNameLike }).then((res: any) => {
      companyNameList.value = res.result.map((item: any) => ({
        label: item.accountEpName,
        value: item.id,
      }))
    })
  }

  const handleSearch = (value: string) => {
    queryCompanyNameList(value)
  }

  const handleOk = () => {
    handleAccountInfo()
    loadData()
  }

  const loginSuccess = (record: any, btnType: string) => {
    // 刷新当前页
    loadData()
    violationQueryVisible.value = true
    violationQueryOptions.value = { ...record, btnType }
  }

  onMounted(() => {
    loadData()
    handleAccountInfo()
    queryCompanyNameList()
  })
</script>

<style scoped lang="less">
  .num {
    color: #1890ff;
  }

  .loginStatus-wrapper {
    height: 28px;
    .loginStatus-icon {
      width: 8px;
      height: 8px;
      border-radius: 50%;
      margin-right: 6px;
      &.open {
        background: #00b42a;
      }
      &.close {
        background: #ea0000;
      }
    }
  }
</style>
